package com.probox.common.entity.service.platfom.impl;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import java.util.Arrays;
import java.util.List;

import com.probox.common.core.constant.CachePrefix;
import com.probox.common.core.enums.CmsLeaf;
import com.probox.common.core.enums.DataStatus;
import com.probox.common.core.exception.BaseException;
import com.probox.common.core.exception.PlatformException;
import com.probox.common.core.utils.DateUtils;
import com.probox.common.core.utils.SecurityUtils;
import com.probox.common.core.utils.StringUtils;
import com.probox.common.redis.service.RedisService;
import com.probox.common.entity.service.platfom.IPlatformCmsClassService;
import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.probox.common.entity.mapper.platfom.PlatformCmsClassMapper;
import com.probox.common.entity.domain.platfom.PlatformCmsClass;
import org.springframework.transaction.annotation.Transactional;

/**
 * 信息分类Service业务层处理
 *
 *
 * @date 2021-06-11
 */
@Service
@Transactional
public class PlatformCmsClassServiceImpl extends ServiceImpl<PlatformCmsClassMapper, PlatformCmsClass> implements IPlatformCmsClassService {
    @Autowired
    private PlatformCmsClassMapper platformCmsClassMapper;

    @Autowired
    private RedisService redisService;

    /**
     * 查询信息分类
     *
     * @param cmsClassUid 信息分类ID
     * @return 信息分类
     */
    @Override
    public PlatformCmsClass selectPlatformCmsClassById(String cmsClassUid) {
        return this.getById(cmsClassUid);
    }

    /**
     * 查询信息分类列表
     *
     * @param platformCmsClass 信息分类
     * @return 信息分类
     */
    @Override
    public List<PlatformCmsClass> queryList(PlatformCmsClass platformCmsClass) {
        QueryWrapper<PlatformCmsClass> queryWrapper = Wrappers.query();
        Long platformId = SecurityUtils.getPlatformId();
        if (platformId == null) throw new BaseException("当前账号异常");
        queryWrapper.eq("PLATFORM_UID", platformId);
        queryWrapper.ne("DATA_STATUS", DataStatus.delete.getKey());
        if (StringUtils.isNotEmpty(String.valueOf(platformCmsClass.getCmsClassName())) && platformCmsClass.getCmsClassName() != null) {
            queryWrapper.like("CMS_CLASS_NAME", platformCmsClass.getCmsClassName());
        }

        if (StringUtils.isNotEmpty(String.valueOf(platformCmsClass.getCmsClassPname())) && platformCmsClass.getCmsClassPname() != null) {
            queryWrapper.eq("CMS_CLASS_PNAME", platformCmsClass.getCmsClassPname());
        }

        if (StringUtils.isNotEmpty(String.valueOf(platformCmsClass.getDataStatus())) && platformCmsClass.getDataStatus() != null) {
            queryWrapper.eq("DATA_STATUS", platformCmsClass.getDataStatus());
        }

        if (StringUtils.isNotEmpty(String.valueOf(platformCmsClass.getIsCmsLeaf())) && platformCmsClass.getIsCmsLeaf() != null) {
            queryWrapper.eq("IS_CMS_LEAF", platformCmsClass.getCmsClassName());
        }
        return platformCmsClassMapper.selectList(queryWrapper);
    }

    @Override
    public List<PlatformCmsClass> queryCategoryList() {
        QueryWrapper<PlatformCmsClass> queryWrapper = Wrappers.query();
        Long platformId = SecurityUtils.getPlatformId();
        if (platformId == null) throw new BaseException("当前账号异常");
        queryWrapper.eq("PLATFORM_UID", platformId);
        queryWrapper.eq("DATA_STATUS", DataStatus.valid.getKey());
        queryWrapper.eq("CMS_CLASS_PNAME", "关于我们");
        return platformCmsClassMapper.selectList(queryWrapper);
    }

    /**
     * 新增信息分类
     *
     * @param platformCmsClass 信息分类
     * @return 结果
     */
    @Override
    public boolean insertPlatformCmsClass(PlatformCmsClass platformCmsClass) {
        if(ObjectUtil.isEmpty(platformCmsClass.getPlatformUid())){
            platformCmsClass.setPlatformUid(SecurityUtils.getPlatformId());
            Integer result = queryCmsClassName(platformCmsClass.getCmsClassName(), null, null);
            if(result > 0) throw new PlatformException("信息分类已存在！");
        }else{
            Integer result = queryCmsClassName(platformCmsClass.getCmsClassName(), null, platformCmsClass.getPlatformUid());
            if(result > 0) throw new PlatformException("信息分类已存在！");
        }
        Long uid = SecurityUtils.getUserId();
        String username = SecurityUtils.getUsername();
        DateTime date = DateUtil.date();
        platformCmsClass.setCreateUid(uid);
        platformCmsClass.setCreateName(username);
        platformCmsClass.setCreateTime(date);
        platformCmsClass.setUpdateUid(uid);
        platformCmsClass.setUpdateName(username);
        platformCmsClass.setUpdateTime(date);
            platformCmsClass.setCmsClassCode(ToPinyin(platformCmsClass.getCmsClassName()));
        return this.save(platformCmsClass);
    }

    /**
     * 修改信息分类
     *
     * @param platformCmsClass 信息分类
     * @return 结果
     */
    @Override
    public boolean updatePlatformCmsClass(PlatformCmsClass platformCmsClass) {
        Integer result = queryCmsClassName(platformCmsClass.getCmsClassName(), platformCmsClass.getCmsClassUid(),null);
        if(result > 0) throw new PlatformException("信息分类已存在！");
        Long uid = SecurityUtils.getUserId();
        String username = SecurityUtils.getUsername();
        DateTime date = DateUtil.date();
        platformCmsClass.setUpdateUid(uid);
        platformCmsClass.setUpdateName(username);
        platformCmsClass.setUpdateTime(date);
        return this.updateById(platformCmsClass);
    }

    /**
     * 批量删除信息分类
     *
     * @param cmsClassUids 需要删除的信息分类ID
     * @return 结果
     */
    @Override
    public boolean deletePlatformCmsClassByIds(String[] cmsClassUids) {
        UpdateWrapper<PlatformCmsClass> updateWrapper = new UpdateWrapper<>();
        updateWrapper.in("CMS_CLASS_UID", Arrays.asList(cmsClassUids));
        updateWrapper.set("DATA_STATUS", DataStatus.delete.getKey());
        updateWrapper.set("UPDATE_UID", SecurityUtils.getUserId());
        updateWrapper.set("UPDATE_NAME", SecurityUtils.getUsername());
        updateWrapper.set("UPDATE_TIME", DateUtil.date());
        return this.update(updateWrapper);
    }

    /**
     *  汉字转拼音
     * @param chinese
     * @return
     */
    private  String ToPinyin(String chinese){
        String pinyinStr = "";
        char[] newChar = chinese.toCharArray();
        HanyuPinyinOutputFormat defaultFormat = new HanyuPinyinOutputFormat();
        defaultFormat.setCaseType(HanyuPinyinCaseType.LOWERCASE);
        defaultFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
        String[] tmp = null;
        for (int i = 0; i < newChar.length; i++) {
            if (newChar[i] > 128) {
                try {
                    tmp = PinyinHelper.toHanyuPinyinStringArray(newChar[i], defaultFormat);
                    if (tmp != null) {
                        pinyinStr += tmp[0];
                    }
                } catch (BadHanyuPinyinOutputFormatCombination e) {
                    e.printStackTrace();
                }
            }else{
                pinyinStr += newChar[i];
            }
        }
        QueryWrapper<PlatformCmsClass> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("CMS_CLASS_CODE", pinyinStr);
        queryWrapper.ne("DATA_STATUS", DataStatus.delete.getKey());
        queryWrapper.eq("PLATFORM_UID",SecurityUtils.getPlatformId());
        Integer integer = platformCmsClassMapper.selectCount(queryWrapper);
        if(integer >0){
            pinyinStr=pinyinStr+DateUtils.dateTime();
        }
        return pinyinStr;
    }

    /**
     * 查询类别重名
     *
     * @param name 名字
     * @param uid  类别ID
     * @return
     */
    private Integer queryCmsClassName(String name, Long uid,Long plaformUid) {
        QueryWrapper<PlatformCmsClass> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("CMS_CLASS_NAME", name);
        queryWrapper.ne("DATA_STATUS", DataStatus.delete.getKey());
        if(ObjectUtil.isEmpty(plaformUid)){
            queryWrapper.eq("PLATFORM_UID", SecurityUtils.getPlatformId());
        }else queryWrapper.eq("PLATFORM_UID", plaformUid);
        if (uid != null) queryWrapper.ne("CMS_CLASS_UID", uid);
        Integer integer = platformCmsClassMapper.selectCount(queryWrapper);
        return integer;
    }


    /**
     *  获得类别下拉框的数据
     * @param level
     * @return
     */
    public List<PlatformCmsClass> bulidSelect(String level){
        PlatformCmsClass platformCmsClass = new PlatformCmsClass();
        platformCmsClass.setIsCmsLeaf(level);
        String key = CachePrefix.PLATFORM_CMS_CLASS+level+SecurityUtils.getPlatformId();
        List<PlatformCmsClass> cacheList = redisService.getCacheList(key);
        if(ObjectUtil.isNotEmpty(cacheList)){
            cacheList = queryList(platformCmsClass);
            if(ObjectUtil.isNotEmpty((cacheList))) redisService.setCacheList(key, cacheList);
        }
        return cacheList;
    }



}
